package com.zanglikun.rocketmq.filter.sql;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @Author: zanglikun
 * @Date: 2022/3/31 20:47
 * @Description: sql消息过滤，注意只有满足sql的结果才能被发现
 * 异常信息：The broker does not support consumer to filter message by SQL92 说的是不支持92sql模式，请在RocketMQ所有节点开启一下 enablePropertyFilter=true
 * <p>
 * SQL过滤支持的类型
 * - 数值，比如：123，3.1415；
 * - 字符，比如：'abc'，必须用单引号包裹起来；
 * - NULL，特殊的常量
 * - 布尔值，TRUE 或 FALSE
 * <p>
 * 场景描述：理解成sql预计查询where条件即可！
 * 标记字段是 a
 * - a > 100
 * - a > 100 and b > 10
 * - a is null or a is not null
 * - a = 'abc'
 */
public class SqlConsumer {
    public static void main(String[] args) throws Exception {
        // todo 1 创建消费者，同时指定消费组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        // todo 2 指定NameServer
        consumer.setNamesrvAddr("192.168.253.128:9876;192.168.253.129:9876");
        // todo 3 订阅主题 同时设定sql过滤 生产者生产消息时，需要额外指定使用 putUserProperty 标记消息
        consumer.subscribe("FilterSQLTopic", MessageSelector.bySql("i>5"));
        // todo 4 设置回调函数，以消费消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                list.forEach(messageExt -> {
                    System.out.println(new String(messageExt.getBody()));
                });
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // todo 5 启动消费者
        consumer.start();
        System.out.println("消费者启动");
    }
}
